<?php
/**
 * Service_Essence
 *
 * Класс Service_Essence осуществляет работу с типами сущностей (ID, имя)
 *
 * @author Дмитий Кузьма <kouzma.d@gmail.com>
 * @author Гринько Виталий <perlaws@gmail.com>
 * @author Aleksandr Egorov <slamer86@gmail.com>
 * @version 2.0
 */
class Service_Essence extends ActiveRecord {

	protected static $_tableName = 'essence_name';
	protected static $_pkName = 'ID_essence_type';
	public $users = null;
	// Массив типов сущностей (ключ - ID_essence) 
	protected static $_arrEssenceTypes = array(
		1 => array(
			'ID_essence_type' => 1,
			'essence_name' => 'administration',
			'human_name' => 'Администратор',
			'class' => null,
			'view_class' => null,
			'name' => null,
		),
		2 => array(
			'ID_essence_type' => 2,
			'essence_name' => 'user',
			'human_name' => 'Пользователь',
			'class' => 'User_User',
			'view_class' => 'View_User',
			'name' => null,
		),
	 	3 => array(
			'ID_essence_type' => 3,
			'essence_name' => 'faq',
			'human_name' => 'FAQ',
			'class' => 'Faq',
			'view_class' => 'View_Faq',
			'name' => 'faq_name',
		),
  	4 => array(
			'ID_essence_type' => 4,
			'essence_name' => 'faq_section',
			'human_name' => 'Раздел FAQ',
			'class' => 'FaqSection',
			'view_class' => null,
			'name' => null,
		),
  	5 => array(
			'ID_essence_type' => 5,
			'essence_name' => 'article',
			'human_name' => 'Статья',
			'class' => 'Article',
			'view_class' => 'View_Article',
			'name' => null,
		),
  	6 => array(
			'ID_essence_type' => 6,
			'essence_name' => 'hotel',
			'human_name' => 'Отель Booking',
			'class' => 'Booking_Hotel',
			'view_class' => 'View_Hotel',
			'name' => null,
		),
  	7 => array(
			'ID_essence_type' => 7,
			'essence_name' => 'city',
			'human_name' => 'Город',
			'class' => 'City',
			'view_class' => 'View_City',
			'name' => null,
		),
  	8 => array(
			'ID_essence_type' => 8,
			'essence_name' => 'country',
			'human_name' => 'Страна',
			'class' => 'Country',
			'view_class' => 'View_Country',
			'name' => null,
		),
  	9 => array(
			'ID_essence_type' => 9,
			'essence_name' => 'region',
			'human_name' => 'Регион',
			'class' => 'Region',
			'view_class' => 'View_Region',
			'name' => null,
		),
  	10 => array(
			'ID_essence_type' => 10,
			'essence_name' => 'district',
			'human_name' => 'Район',
			'class' => 'District',
			'view_class' => null,
			'name' => null,
		),
  	11 => array(
			'ID_essence_type' => 11,
			'essence_name' => 'room',
			'human_name' => 'Номер',
			'class' => 'Booking_Room',
			'view_class' => null,
			'name' => null,
		),
  	12 => array(
			'ID_essence_type' => 12,
			'essence_name' => 'booking',
			'human_name' => 'Бронирование',
			'class' => 'Booking',
			'view_class' => 'View_Booking',
			'name' => null,
		),
  	13 => array(
			'ID_essence_type' => 13,
			'essence_name' => 'our_hotel_photo',
			'human_name' => 'Фото extranet отеля',
			'class' => 'Extranet_Hotel_Photo',
			'view_class' => null,
			'name' => null,
		),
  	14 => array(
			'ID_essence_type' => 14,
			'essence_name' => 'our_room_photo',
			'human_name' => 'Фото extranet номера',
			'class' => 'Extranet_Room_Photo',
			'view_class' => null,
			'name' => null,
		),
	15 => array(
			'ID_essence_type' => 15,
			'essence_name' => 'our_hotel',
			'human_name' => 'Extranet отель',
			'class' => 'Extranet_Hotel',
			'view_class' => 'View_Hotel',
			'name' => null,
		),
  	16 => array(
			'ID_essence_type' => 16,
			'essence_name' => 'our_room',
			'human_name' => 'Extranet номер',
			'class' => 'Extranet_Room',
			'view_class' => 'View_OurRoom',
			'name' => null,
		),
  	17 => array(
			'ID_essence_type' => 17,
			'essence_name' => 'our_hotel_children_policy',
			'human_name' => 'Extranet условия проживания детей',
			'class' => 'Extranet_Hotel_ChildrenPolicy',
			'view_class' => null,
			'name' => null,
		),
  	18 => array(
			'ID_essence_type' => 18,
			'essence_name' => 'place',
			'human_name' => 'Достопримечательность',
			'class' => 'Place',
			'view_class' => 'View_Place',
			'name' => null,
		),
  	19 => array(
			'ID_essence_type' => 19,
			'essence_name' => 'post',
			'human_name' => 'Пост в блоге',
			'class' => 'Post',
			'view_class' => null,
			'name' => null,
		),
  	20 => array(
			'ID_essence_type' => 20,
			'essence_name' => 'comment',
			'human_name' => 'Комментарий',
			'class' => 'Comment',
			'view_class' => 'View_Comment',
			'name' => null,
		),
  	21 => array(
			'ID_essence_type' => 21,
			'essence_name' => 'hit',
			'human_name' => 'Посещение страницы',
			'class' => 'Hit',
			'view_class' => null,
			'name' => null,
		),
  	22 => array(
			'ID_essence_type' => 22,
			'essence_name' => 'contest_hotel',
			'human_name' => 'Конкурсный отель',
			'class' => 'Contest_Hotel',
			'view_class' => null,
			'name' => null,
		),
  	23 => array(
			'ID_essence_type' => 23,
			'essence_name' => 'contest_hotel_photo',
			'human_name' => 'Фото конкурсного отеля',
			'class' => 'Contest_HotelPhoto',
			'view_class' => null,
			'name' => null,
		),
  	24 => array(
			'ID_essence_type' => 24,
			'essence_name' => 'contest_nomination',
			'human_name' => 'Номинация конкурса',
			'class' => 'Contest_Nomination',
			'view_class' => null,
			'name' => null,
		),
  	25 => array(
			'ID_essence_type' => 25,
			'essence_name' => 'contest_criterion',
			'human_name' => 'Критерий конкурса',
			'class' => 'Contest_Criterion',
			'view_class' => null,
			'name' => null,
		),
  	26 => array(
			'ID_essence_type' => 26,
			'essence_name' => 'block_compare',
			'human_name' => 'Блок для сравнения',
			'class' => null,
			'view_class' => 'View_Compare',
			'name' => null,
		),
  	27 => array(
			'ID_essence_type' => 27,
			'essence_name' => 'review',
			'human_name' => 'Отзыв',
			'class' => 'Review',
			'view_class' => 'View_Review',
			'name' => null,
		),
  	28 => array(
			'ID_essence_type' => 28,
			'essence_name' => 'invite_to_review',
			'human_name' => 'Приглашение оставить отзыв',
			'class' => 'InviteToReview',
			'view_class' => null,
			'name' => null,
		),
  	29 => array(
			'ID_essence_type' => 29,
			'essence_name' => 'old_hotels',
			'human_name' => 'Старый отель',
			'class' => null,
			'view_class' => null,
			'name' => null,
		),
  	30 => array(
			'ID_essence_type' => 30,
			'essence_name' => 'hrs_hotel',
			'human_name' => 'HRS отель',
			'class' => 'Hrs_Hotel',
			'view_class' => 'View_Hotel',
			'name' => null,
		),
  	31 => array(
			'ID_essence_type' => 31,
			'essence_name' => 'hrs_location',
			'human_name' => 'HRS город',
			'class' => 'Hrs_Location',
			'view_class' => null,
			'name' => null,
		),
  	32 => array(
			'ID_essence_type' => 32,
			'essence_name' => 'common_hotel',
			'human_name' => 'Общий отель',
			'class' => 'Common_Hotel',
			'view_class' => 'View_Hotel',
			'name' => null,
		),
  	33 => array(
			'ID_essence_type' => 33,
			'essence_name' => 'common_room',
			'human_name' => 'Общий номер',
			'class' => 'Common_Room',
			'view_class' => 'View_Room',
			'name' => null,
		),
  	34 => array(
			'ID_essence_type' => 34,
			'essence_name' => 'common_room_description',
			'human_name' => 'Описание общего номера',
			'class' => 'Common_Room_Description',
			'view_class' => null,
			'name' => null,
		),
  	35 => array(
			'ID_essence_type' => 35,
			'essence_name' => 'common_room_facility',
			'human_name' => 'Услуга общего номера',
			'class' => 'Common_Room_Facility',
			'view_class' => null,
			'name' => null,
		),
  	36 => array(
			'ID_essence_type' => 36,
			'essence_name' => 'common_room_photo',
			'human_name' => 'Фото общего номера',
			'class' => 'Common_Room_Photo',
			'view_class' => null,
			'name' => null,
		),
  	40 => array(
			'ID_essence_type' => 40,
			'essence_name' => 'common_hotel_photo',
			'human_name' => 'Фото общего отеля',
			'class' => 'Common_Hotel_Photo',
			'view_class' => null,
			'name' => null,
		),
  	41 => array(
			'ID_essence_type' => 41,
			'essence_name' => 'common_hotel_description',
			'human_name' => 'Описание общего отеля',
			'class' => 'Common_Hotel_Description',
			'view_class' => null,
			'name' => null,
		),
  	42 => array(
			'ID_essence_type' => 42,
			'essence_name' => 'common_hotel_facility',
			'human_name' => 'Услуга общего отеля',
			'class' => 'Common_Hotel_Facility',
			'view_class' => null,
			'name' => null,
		),
  	43 => array(
			'ID_essence_type' => 43,
			'essence_name' => 'common_hotel_credit_card',
			'human_name' => 'Кредитка общего отеля',
			'class' => 'Common_Hotel_CreditCard',
			'view_class' => null,
			'name' => null,
		),
  	44 => array(
			'ID_essence_type' => 44,
			'essence_name' => 'experiment',
			'human_name' => 'Эксперимент',
			'class' => 'Experiment',
			'view_class' => 'View_Experiment',
			'name' => null,
		),
  	45 => array(
			'ID_essence_type' => 45,
			'essence_name' => 'page_type',
			'human_name' => 'Тип страницы',
			'class' => 'PageType',
			'view_class' => 'View_PageType',
			'name' => null,
		),
  	46 => array(
			'ID_essence_type' => 46,
			'essence_name' => 'experiment_variant',
			'human_name' => 'Вариант эксперимента',
			'class' => 'Experiment_Variant',
			'view_class' => 'View_Experiment_Variant',
			'name' => null,
		),
  	47 => array(
			'ID_essence_type' => 47,
			'essence_name' => 'experiment_essence',
			'human_name' => 'Сущность эксперимента',
			'class' => 'Experiment_Essence',
			'view_class' => 'View_Experiment_Essence',
			'name' => null,
		),
  	48 => array(
			'ID_essence_type' => 48,
			'essence_name' => 'experiment_variant_info',
			'human_name' => 'Данные варианта эксперимента',
			'class' => 'Experiment_VariantInfo',
			'view_class' => null,
			'name' => null,
		),
  	49 => array(
			'ID_essence_type' => 49,
			'essence_name' => 'experiment_click',
			'human_name' => 'Клики эксперимента',
			'class' => 'Experiment_Click',
			'view_class' => null,
			'name' => null,
		),
  	50 => array(
			'ID_essence_type' => 50,
			'essence_name' => 'ostrovok_location',
			'human_name' => 'Ostrovok город',
			'class' => 'Ostrovok_Location',
			'view_class' => null,
			'name' => null,
		),
	51 => array(
			'ID_essence_type' => 51,
			'essence_name' => 'contest_hotel_nomination',
			'human_name' => 'Конкурсный отель в номинации',
			'class' => 'Contest_HotelNomination',
			'view_class' => null,
			'name' => null,
		),
	52 => array(
			'ID_essence_type' => 52,
			'essence_name' => 'session',
			'human_name' => 'Сессия пользователя',
			'class' => 'User_Session',
			'view_class' => null,
			'name' => null,
		),
	53 => array(
		'ID_essence_type' => 53,
		'essence_name' => 'popular_query',
		'human_name' => 'Популярные запросы',
		'class' => 'PopularQuery',
		'view_class' => null,
		'name' => null,
	),
	54 => array(
		'ID_essence_type' => 54,
		'essence_name' => 'report_admin_location',
		'human_name' => 'Сообщение о месторасположении',
		'class' => 'ReportAdminLocation',
		'view_class' => null,
		'name' => null
	),
	55 => array(
		'ID_essence_type' => 55,
		'essence_name' => 'booking_change',
		'human_name' => 'Изменение в бронировании',
		'class' => 'BookingChange',
		'view_class' => null,
		'name' => null
	),
	56 => array(
		'ID_essence_type' => 56,
		'essence_name' => 'support_request',
		'human_name' => 'Запрос в службу поддержки',
		'class' => 'SupportRequest',
		'view_class' => 'View_SupportRequest',
		'name' => null
	),
	57 => array(
		'ID_essence_type' => 57,
		'essence_name' => 'booking_step',
		'human_name' => 'Шаг бронирования',
		'class' => 'BookingStep',
		'view_class' => 'View_BookingStep',
		'name' => null
	),
	58 => array(
		'ID_essence_type' => 58,
		'essence_name' => 'support_task',
		'human_name' => 'Задача TODO-листа',
		'class' => 'SupportTask',
		'view_class' => null,
		'name' => null
	),
	59 => array(
		'ID_essence_type' => 59,
		'essence_name' => 'forum_topic',
		'human_name' => 'Тема на форуме',
		'class' => 'ForumTopic',
		'view_class' => 'View_Forum',
		'name' => null
	),
	60 => array(
		'ID_essence_type' => 60,
		'essence_name' => 'forum_message',
		'human_name' => 'Сообщение на форуме',
		'class' => 'ForumMessage',
		'view_class' => 'View_Forum',
		'name' => null
	),
	61 => array(
		'ID_essence_type' => 61,
		'essence_name' => 'nearest_arrival',
		'human_name' => 'Ближайшие заезды',
		'class' => 'NearestArrival',
		'view_class' => 'View_Booking',
		'name' => null
	),
	62 => array(
		'ID_essence_type' => 62,
		'essence_name' => 'booking_block',
		'human_name' => 'Забронированный номер',
		'class' => 'BookingBlock',
		'view_class' => null,
		'name' => null
	),
	63 => array(
		'ID_essence_type' => 63,
		'essence_name' => 'incoming_mail',
		'human_name' => 'Входящее письмо',
		'class' => 'IncomingMail',
		'view_class' => null,
		'name' => null
	),
	64 => array(
		'ID_essence_type' => 64,
		'essence_name' => 'callback_request',
		'human_name' => 'Обратный запрос',
		'class' => 'CallbackRequest',
		'view_class' => 'View_CallbackRequest',
		'name' => null
	),
	65 => array(
		'ID_essence_type' => 65,
		'essence_name' => 'support_notice',
		'human_name' => 'Уведомление админам',
		'class' => 'SupportNotice',
		'view_class' => null,
		'name' => null
	),
	66 => array(
		'ID_essence_type' => 66,
		'essence_name' => 'booking_no_cc',
		'human_name' => 'Бронирования без кредитки',
		'class' => 'BookingNoCC',
		'view_class' => null,
		'name' => null
	),
	67 => array(
		'ID_essence_type' => 67,
		'essence_name' => 'support_answer',
		'human_name' => 'Ответ СП',
		'class' => 'SupportAnswer',
		'view_class' => null,
		'name' => null
	),
	68 => array(
		'ID_essence_type' => 68,
		'essence_name' => 'chm_travelline_hotel',
		'human_name' => 'Отель тревеллайна',
		'class' => 'ChM_TravelLine_Hotel',
		'view_class' => null,
		'name' => null
	)
	);

  public function __construct($arrInitialFields = null) {
    Service_Debug::setDebug();
		parent::__construct($arrInitialFields);
		$this->users = new HasMany(array('className' => 'User_User', 'throw' => 'administration'));
  }
  
  /**
   * Возвращаем массив типов сущностей
   * 
   * @return array - Типы сущностей
   */
  public static function getArrEssenceTypes() {
  	return self::$_arrEssenceTypes;
  }

  /**
   * Определяет существует ли тип сущности 
   * 
   * @param string $essenceType - тип сущности
   */
  public static function isEssenceTypeCorrect($essenceType) {
		$arrEssenceNames = Service_ArrayConverter::getColumn(self::$_arrEssenceTypes, 'essence_name'); 
		if (in_array($essenceType, $arrEssenceNames))	return true;
		return false;
  }
  
  /**
   * Получение имени сущности по идентификатору
   *
   * @param int $essenceNumber
   * @return string
   */
  public static function getEssenceTypeName($essenceType) {
  	if (is_numeric($essenceType)) return self::getEssenceTypeNameById($essenceType);
    elseif (!is_string($essenceType)) {
    	throw new Exception('Invalid input numeric / string value type entity (type = 1)');
    }
    if (self::isEssenceTypeNameCorrect($essenceType)) return $essenceType;
    else return false;
  }

  /**
   * Метод получает объект нужного типа. Объект будет сразу наполнен информацией, если передать id. Если этого делать не нужно, передайте null
   *
   * @param mixed $essenceType
   * @param integer $id
   * @return ActiveRecord - Объект
   */
  public static function getObjByID($essenceType, $essenceId = null) {
  	$essenceTypeId = self::getEssenceTypeID($essenceType);
  	$class = @self::$_arrEssenceTypes[$essenceTypeId]['class'];
  	if ($class) return new $class($essenceId); 
    return false;
  }

  /**
   * Возвращаем название сущности по ее типу
   *
   * @param mixed $essenceType - Тип сущности
   */
  public static function getHumanEssenceName($essenceType) {
  	$essenceTypeId = self::getEssenceTypeID($essenceType);
  	return @self::$_arrEssenceTypes[$essenceTypeId]['human_name'];
  }

  /**
   * Метод получает View объект нужного типа.
   *
   * @param mixed $essenceType
   * @return View_Base
   */
  public static function getViewObjByID($essenceType, $essenceId = null) {
    $essenceTypeId = self::getEssenceTypeID($essenceType);
  	$class = @self::$_arrEssenceTypes[$essenceTypeId]['view_class'];
  	if ($class) return new $class($essenceId); 
    return false;
  }

  /**
   * Получение имени сущности по идентификатору
   *
   * @param int $essenceTypeId - ID типа сущности
   * @return string - Тип сущности
   */
  public static function getEssenceTypeNameById($essenceTypeId) {
  	return @self::$_arrEssenceTypes[$essenceTypeId]['essence_name'];
  }

  /**
   * Получение идентификатора сущности по имени
   *
   * @param string $essenceName
   * @return int
   */
  public static function getEssenceTypeIDByName($essenceName) {
  	$arrEssenceTypes = Service_ArrayConverter::makeKeySimpleArrayFromMultyArray(self::$_arrEssenceTypes, 'essence_name', 'ID_essence_type');
  	return @$arrEssenceTypes[$essenceName];
  }

  /**
   * Получение идентификатора сущности по любому параметру
   *
   * @param mixed $essenceType
   * @return int
   */
  public static function getEssenceTypeID($essenceType) {
  	if (self::isEssenceTypeIdCorrect($essenceType) && is_numeric($essenceType)) return $essenceType;
    if (is_string($essenceType)) return intval(self::getEssenceTypeIDByName($essenceType));
    elseif (!is_numeric($essenceType)) throw new Exception('Invalid input numeric / string value type entity (type = 4)');
    if (self::isEssenceTypeIdCorrect($essenceType)) return $essenceType;
    else return false;
  }

  /**
   * Метод проверяет, корректно ли указан идентификатор типа сущности
   *
   * @param integer $essenceTypeId
   * @return boolean
   */
  public static function isEssenceTypeIDCorrect($essenceTypeId) {
    return self::getEssenceTypeNameById($essenceTypeId) ? true : false;
  }

  /**
   * Метод проверяет, корректно ли указан идентификатор типа сущности
   *
   * @param integer $essenceTypeId
   * @return boolean
   */
  public static function isEssenceTypeNameCorrect($essenceTypeName) {
    return self::getEssenceTypeIDByName($essenceTypeName) ? true : false;
  }
  
  /**
   * Возвращаем название объекта по типу сущности
   *
   * @param mixed $essenceType - Тип сущности
   * @param array $arrData - Массив с данными о названии
   * @return string - Имя объекта
   */
  public static function getNameOfObject($essenceType, array $arrData) {
  	$objView = self::getViewObjByID($essenceType);
    if ($objView) return $objView->getName($arrData);
    else return null;
  }  
  
  /**
   * Проверяет, совпадает ли пользователь с автором
   *
   * @param integer $essenceType
   * @param integer $essenceID
   * @param integer $userId
   */
  public static function isAuthorTheSame($essenceType, $essenceId, $userId = null) {
    if (!$userId) {
      $objSession = User_Session::instance();
      $userId = $objSession->getUserId();
    }
    if (!$userId) return false;
    $strTable = Service_Essence::getEssenceTypeName($essenceType);
	  $objDB = Service_Database::instance();
		$stmt = "SELECT `ID_user` FROM `" . $strTable . "`
				WHERE `ID_" . $strTable . "`='" . $essenceId . "' AND `ID_user`='" . $userId . "'";
    return (sizeof($objDB->selectOne($stmt)) > 0) ? true : false;  //Осуществляем SQL-запрос
  }

  /**
   * получает автора материала
   *
   * @param integer $essenceType
   * @param integer $essenceID
   */
  public static function getAuthor($essenceType, $essenceId) {
    $strTable = Service_Essence::getEssenceTypeName($essenceType);
	  $objDB = Service_Database::instance();
		$stmt = "SELECT `ID_user` FROM `" . $strTable . "`
				WHERE `ID_" . $strTable . "`='" . $essenceId . "'";
    return $objDB->selectSimpleField($stmt);  //Осуществляем SQL-запрос
  }

	/**
	 * Возвращает условие JOIN для запроса mysql исходя из типов сущности
	 * 
	 * @param array $arrEssenceTypeIds - Типы сущностей
	 * @param string $mainTable - Название основной таблицы
	 * @return string - JOINS
	 */
  public static function makeJoinsByEssenceTypeIds(array $arrEssenceTypeIds, $mainTable) {
    $stmtJoins = "";
    $arrEssenceTypeIds = array_unique($arrEssenceTypeIds);
    foreach ($arrEssenceTypeIds as $essenceTypeId) {
    	$class = @self::$_arrEssenceTypes[$essenceTypeId]['class'];
    	if (!$class) continue;
    	$tableName = $class::getTableName();
     	$stmtJoins .= " LEFT JOIN `" . $tableName . "` ON `" . $tableName . "`.`" . $class::getPkName() . "` = `" . $mainTable . "`.`ID_essence` AND `" . $mainTable . "`.`ID_essence_type` = " . $essenceTypeId;
    }
    return $stmtJoins;
  }

	/**
	 * Возвращает условие SELECT для запроса mysql исходя из типов сущности
	 * 
	 * @param array $arrEssenceTypeIds - Типы сущностей
	 * @return string - JOINS
	 */
  public static function makeSelectByEssenceTypeIds(array $arrEssenceTypeIds) {
    $stmtSelect = "";
    $arrEssenceTypeIds = array_unique($arrEssenceTypeIds);
    foreach ($arrEssenceTypeIds as $essenceTypeId) {
    	$class = @self::$_arrEssenceTypes[$essenceTypeId]['class'];
    	if (!$class) continue;
    	$tableName = $class::getTableName();
    	$stmtSelect .= ",`" . $tableName . "`.*";
    }
    return $stmtSelect;
  }

  	/**
	 * Инкремент поля для сущности
	 *
	 * @param string $essenceName - Имя сущности
	 * @param int $essenceId - ID сущности
	 * @param string $columnName - поле для инкремента
	 * @return unknown
	 */
  public static function incrementColumnInEssecnce($essenceName, $essenceId, $columnName, $count = 1, $pkName = null) {
  	$essenceName = Service_Essence::getEssenceTypeName($essenceName);
  	if (!$pkName) {
  		$objEssence = Service_Essence::getObjByID($essenceName, $essenceId);
  		$pkName = $objEssence->getPkName();
  		$table = $objEssence->getTableName();
  	}
  	else $table = $essenceName;
  	if (!$pkName) $pkName = "ID_" . $essenceName;
		$objDB = Service_Database::instance();
		$stmt = "
		UPDATE `" . $table . "` SET `" . $table . "`.`" . $columnName . "` = (`" . $table . "`.`" . $columnName . "` + " . $count . ")
		WHERE `" . $table . "`.`" . $pkName . "` = '" . $essenceId . "'";

		$res = $objDB->query($stmt);
		return $res;
	}

	/**
	 * Декремент поля для сущности
	 *
	 * @param string $essenceName - Имя сущности
	 * @param int $essenceId - ID сущности
	 * @param string $columnName - поле для декремента
	 * @return unknown
	 */
  public static function decrementColumnInEssecnce($essenceName, $essenceId, $columnName, $count = 1, $pkName = null) {
  	if (!$pkName) $pkName = "ID_" . $essenceName;
		$objDB = Service_Database::instance();
		$objEssence = self::getObjByID($essenceName);
		$stmt = "UPDATE `" . $essenceName . "` SET `" . $essenceName . "`.`" . $columnName . "` = (`" . $essenceName . "`.`" . $columnName . "` - " . $count . ")
		WHERE `" . $essenceName . "`.`" . $pkName . "` = '" . $essenceId . "'";
		return $objDB->query($stmt);
	}

	public static function &getEssencesList(array &$arrIn, $fieldsList = array()) {
		$arrOut = array();		
		$arrTemp = Service_ArrayConverter::splitArrayByField($arrIn, 'essenceType');
		$arrKeys = array();
		
		if($fieldsList) {
			foreach (array_keys($arrTemp) as $essenceType) {
				$objEssence = self::getObjByID($essenceType);
				$tableFields = array_keys($objEssence->getDbInfo());
				$fields = array();
				foreach ($fieldsList as $field) {
					if($field == 'PK!') $field = $objEssence->getPkName();
					if($field == 'NAME!') $field = array($objEssence->getTableName() . '_final_name', $objEssence->getTableName() . '_name');
					$field = (array)$field;
					
					foreach($field as $key => $item) {
						if(preg_match('#(_final)?_name$#i', $item)) {
							$field[] = $item . '_en'; 
							$field[] = $item . '_ru';
							unset($field[$key]);
						}
					}
					
					$fields = array_merge($fields, $field);
				}
				
				$tableFields = array_intersect($tableFields, $fields);
				$arrKeys[$essenceType] = $tableFields;
			}
		}
		
		foreach($arrTemp as $essenceType => &$arrEssences) {
			$ids = '\'' . implode('\', \'', Service_ArrayConverter::getColumn($arrEssences, 'essenceId')) . '\'';
			$objEssence = self::getObjByID($essenceType);
			$pkName = $objEssence->getPkName();
			
			$arrEssencesFull = $objEssence->find('all', array(
				'select' => isset($arrKeys[$essenceType]) && !empty($arrKeys[$essenceType]) ? '`' . implode('`, `', $arrKeys[$essenceType]) . '` ' : '*',
				'conditions' => $pkName . " IN (" . $ids . ")",
// 				'order' => "FIELD(" . $pkName . ", " . $ids . ")"
			));
			
			$arrEssences = Service_ArrayConverter::makeKeyArrayFromMultyArray($arrEssences, 'essenceId', true);
			$arrEssencesFull = Service_ArrayConverter::makeKeyArrayFromMultyArray($arrEssencesFull, $pkName, true);
			
			foreach($arrEssences as $id => &$item) {
				if(!isset($arrEssencesFull[$id])) {
					unset($arrEssences[$id]);
				}
				else {
					$item = Service_ArrayConverter::arrayMergeRecursiveDistinct($item, $arrEssencesFull[$id]);					
				}
			}
			
			unset($arrEssencesFull);
		}
		
		foreach($arrIn as $id => $item_) {
			if(isset($arrTemp[$item_['essenceType']][$item_['essenceId']])) {
				$arrOut[] = $arrTemp[$item_['essenceType']][$item_['essenceId']];
			}
			unset($arrTemp[$item_['essenceType']][$item_['essenceId']]);
		}
		
		return $arrOut;
	}
}
?>